package com.itheima.health.controller.user;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.MemberDao;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.SMS;
import com.itheima.health.service.VerificationService;
import com.itheima.health.util.BduyunSms;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 张博源
 * @date 2024-04-16
 */
@RestController
@RequestMapping("/mobile")
@Slf4j
public class Login {
    @Autowired
    private  BduyunSms bduyunSms;
    @Autowired
    private VerificationService verificationService;
    @Autowired
    private MemberDao memberDao;
    @PostMapping("/validateCode/send")
    public Result sendValidateCode (SMS sms){
        // 一分钟内禁止再次发送短信
        // Boolean flag = verificationService.verifyCodeRepeat(RedisConst.BUSINESS_SMS_LOGIN, sms.getTelephone());
        // if(!flag){
        // return new Result(false, MessageConst.TELEPHONE_VALIDATECODE_REPORT);
        // }
        String code = bduyunSms.sendSms(sms.getTelephone());
        if(code!=null){
            verificationService.sendVerificationCode(sms.getType(),sms.getTelephone(),code);
            Integer i = memberDao.selectByphoneNumber(sms.getTelephone());
            if(i==0){
                memberDao.insertMember(sms.getTelephone());
            }
            return new Result(true, MessageConst.SEND_VALIDATECODE_SUCCESS );
        }else{
            return new Result(true, MessageConst.SEND_VALIDATECODE_FAIL );
        }
    }
    @PostMapping("/login/smsLogin")
    public Result verifyCode(@RequestBody SMS sms){
        return verificationService.verifyCode("MOBILE_SIGNIN",sms.getTelephone(),sms.getValidateCode());
    }
}
